<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { map } from 'lodash'
import { ElMessageBox } from 'element-plus'
import CategoryModel from '@/models/CategoryModel'
import AddClusterDialog from './AddClusterDialog.vue'
import DeleteButton from '@/components/DeleteButton.vue'
import EditButton from '@/components/EditButton.vue'
import { GapedColumn, Section } from '@/core/components'
import AddButton from '@/components/AddButton.vue'
import useApi from '@/core/apiStore'
import {
  showSuccessDeleteMessage,
  showConfirm,
  checkDuplicateCondition,
  showSuccessSaveMessage,
  showAlert,
} from '@/utils'

const apiStore = useApi()

const addClusterDialog = ref(null)
const categories = ref<CategoryModel[]>([])
const computedCategories = computed(() => {
  return map(categories.value, (category, index) => ({
    id: index,
    ...category,
  }))
})

onMounted(async () => {
  const {
    data: { clusters = [] },
  } = await apiStore.getClusters()
  categories.value = clusters
})

const handleAdd = () => {
  addClusterDialog.value.show()
}

const handleEdit = (category: CategoryModel) => {
  addClusterDialog.value.show({ ...category })
}

const handleDelete = async (category: CategoryModel) => {
  await showConfirm(`你确定要删除"${category.name}"?`, async () => {
    const index = categories.value.findIndex(c => c.name === category.name)
    if (index !== -1) {
      categories.value.splice(index, 1)
      await apiStore.setClusters({ clusters: categories.value })
      showSuccessDeleteMessage()
    }
  })
}

const handleSave = async (categoryData: CategoryModel) => {
  const isDuplicate = checkDuplicateCondition(
    computedCategories.value,
    categoryData
  )

  if (isDuplicate) {
    showAlert('集群名称已存在，请使用其他名称')
    return false
  }

  // 如果是编辑操作，更新现有条件
  if (categoryData.id !== undefined) {
    const index = computedCategories.value.findIndex(
      c => c.id === categoryData.id
    )
    if (index !== -1) {
      categories.value[index] = { ...categoryData }
    }
  } else {
    // 新增条件
    categories.value.push({
      ...categoryData,
    })
  }

  await apiStore.setClusters({ clusters: categories.value })
  showSuccessSaveMessage()
  return true
}
</script>

<template>
  <Section>
    <GapedColumn>
      <AddButton buttonText="新增集群" @click="handleAdd" />
      <el-table :data="computedCategories" style="width: 100%">
        <el-table-column prop="name" label="集群名称" />
        <el-table-column prop="ips" label="Ips">
          <template #default="{ row }">
            <TagList v-if="row.ips" :items="row.ips" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="warningConditions" label="告警规则">
          <template #default="{ row }">
            <TagList
              v-if="row.warningConditions"
              :items="row.warningConditions"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <EditButton @click="handleEdit(row)" />
            <DeleteButton @click="handleDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
    </GapedColumn>

    <AddClusterDialog ref="addClusterDialog" :saveCallback="handleSave" />
  </Section>
</template>

<style scoped>
.category-management {
  padding: 20px;
}
</style>
